//
//  DDGoodsDetailsViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/16.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDGoodsDetailsViewController.h"
#import "MJRefreshNormalHeader.h"
#import "DDDetailsTitleView.h"
#import "DDShopInfoView.h"
#import "KSScrollMenuView.h"
#import "DDGoodsManager.h"
#import "DDGoodsDetailsObj.h"
#import "DDDetailsSpecView.h"
#import "DDDetailsBottomView.h"
#import "DDShopViewController.h"
#import "KSTabButtonView.h"
#import "DDDetailsCommentView.h"
#import "IQKeyboardManager.h"
#import "DDCommentSet.h"
#import "DDDetailsDescriptionView.h"
#import "DDCartManager.h"
#import "DDUserManager.h"
#import "DDShoppintCartViewController.h"
#import "UIButton+Badge.h"
#import <WebKit/WebKit.h>
#import "TZPhotoPreviewController.h"

typedef NS_ENUM(NSInteger, ScrollViewDirection){
    ScrollViewDirectionVertical = 1,
    ScrollViewDirectionHoritonzal = 2,
} ;

@interface DDGoodsDetailsViewController ()<UIScrollViewDelegate,DDDetailsBottomViewDelegate,KSTabButtonViewDelegate,DDDetailsSpecViewDelegate,DDDetailsCommentViewDelegate,DDDetailsDescriptionViewDelegate>
@property (strong, nonatomic) UIScrollView *bgScrollView;
@property (strong, nonatomic) UIScrollView *subScrollView;
@property (strong, nonatomic) KSTabButtonView *navigationTabView;
@property (strong, nonatomic) DDDetailsTitleView *detailsTitleView;
@property (strong, nonatomic) DDShopInfoView *shopInfoView;
@property (strong, nonatomic) KSScrollMenuView *serviceMenuView;
@property (strong, nonatomic) DDDetailsBottomView *buyView;
@property (assign, nonatomic) CGFloat topHeight;
@property (strong, nonatomic) UIButton *rightItemBtn;
@property (assign, nonatomic) BOOL theGoodsAddToCart;/**<同一商品是否加入购物车一次*/
#pragma mark --- 选择规格
@property (strong, nonatomic) UIViewController *rootViewController;
@property (strong, nonatomic) UIView *maskLayer;
@property (strong, nonatomic) DDDetailsSpecView *popView;
@property (strong, nonatomic) KKLabel *specView;
@property (strong, nonatomic) UIButton *pullBtn;
#pragma mark --- 控制ScrollView滑动方向
@property (nonatomic) CGPoint scrollViewStartPosPoint;
@property (nonatomic) int     scrollDirection;
#pragma mark --- 数据模型
@property (strong, nonatomic) DDGoodsDetailsObj *detailsObj;
@property (strong, nonatomic) DDCommentSet *commentSet;
@property (strong, nonatomic) WKWebView *detailsWebView;
#pragma mark --- 评论view
@property (strong, nonatomic) DDDetailsCommentView *commentView;
@property (assign, nonatomic) NSInteger commentPage;
#pragma mark --- 下面的描述view和评论view
@property (strong, nonatomic) DDDetailsDescriptionView *descriptionView;
@property (strong, nonatomic) KSTabButtonView *subTabView;

@property (strong, nonatomic) DDGoodsManager *manager;
@property (strong, nonatomic) DDCartManager *cartManager;
@property (strong, nonatomic) DDUserManager *userManager;
@end

@implementation DDGoodsDetailsViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([SystemConfig shareInstance].isLogin) {
        [self getCartCount];
        [self checkCollection];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.manager = [DDGoodsManager new];
    self.cartManager = [DDCartManager new];
    self.userManager = [DDUserManager new];
    [self layoutDetailsView];
    [self fetchGoodsDetails];
}
//获取详情
- (void)fetchGoodsDetails
{
    weak_Self(self);
    [[self.manager goodsDetails:self.goods_id]subscribeNext:^(id x) {
        weakSelf.detailsObj = x;
        [weakSelf reloadDetailsInfo];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)checkCollection
{
    weak_Self(self);
    [[self.manager checkGoodsIsCollection:self.goods_id]subscribeNext:^(id x) {
        NSInteger isCollection = [x integerValue];
        if (isCollection == 0) {
            weakSelf.buyView.wished = NO;
        }else{
            weakSelf.buyView.wished = YES;
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
//获取评论
- (void)fetchCommentList:(NSInteger)type commentViewType:(NSString *)top
{
    weak_Self(self);
    [self showHUD];
    [[self.manager getCommentList:self.goods_id grade:type pageNo:self.commentPage pageSize:kPageSize]subscribeNext:^(id x) {
        weakSelf.commentSet = x;
        [weakSelf reloadCommentInfoWithType:top];
    } error:^(NSError *error) {
        
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)reloadDetailsInfo
{
    NSArray *imgAry = self.detailsObj.galleryList;
    __block NSMutableArray *smallAry = [[NSMutableArray alloc]initWithCapacity:0];
    [imgAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DDGoodsGallery *gallery = obj;
        [smallAry addObject:ValidString(gallery.big)];
    }];
    self.detailsTitleView.galleryAry = smallAry;
    self.detailsTitleView.goodsName = self.detailsObj.goods.name;
    self.detailsTitleView.goodsPrice = NumberToString(self.detailsObj.goods.price);
    
    self.shopInfoView.shopName = self.detailsObj.store.store_name;
    self.shopInfoView.logoUrl = self.detailsObj.store.store_logo;
    
    self.popView.specSet = self.detailsObj.spec;
    self.popView.goodsPrice = self.detailsObj.goods.price;
    self.popView.goodsPic = self.detailsObj.goods.thumbnail;
    self.popView.goodsSn = self.detailsObj.goods.sn;
    
    self.descriptionView.goodsInfoUrl = self.detailsObj.goods_info_url;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.detailsObj.goods_info_url]];
    [self.detailsWebView loadRequest:request];
}
- (void)reloadCommentInfoWithType:(NSString *)type
{
    if ([type isEqualToString:@"top"]){
        self.commentView.commentAry = self.commentSet.commentAry;
        if (self.commentView.commentAry.count == 0) {
            [self showNoContentViewIn:self.commentView image:@"no_comment" withOriginY:50 message:@"No evaluate."];
        }else{
            [self hideNoContentView];
        }
    }else if ([type isEqualToString:@"bot"]){
        self.descriptionView.commentAry = self.commentSet.commentAry;
        if (self.descriptionView.commentAry.count == 0) {
            [self showNoContentViewIn:self.descriptionView image:@"no_comment" withOriginY:50 message:@"No evaluate."];
        }else{
            [self hideNoContentView];
        }
    }
}
/**
 底部的scrollView
 */
- (UIScrollView *)bgScrollView
{
    if (!_bgScrollView) {
        _bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-50-64)];
        _bgScrollView.delegate = self;
        _bgScrollView.showsVerticalScrollIndicator = NO;
        _bgScrollView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_bgScrollView];
        self.scrollDirection = 0;
    }
    return _bgScrollView;
}
/**
 下面的scrollView
 */
- (UIScrollView *)subScrollView
{
    if (!_subScrollView) {
        _subScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _topHeight, ScreenWidth, ScreenHeight-64-50)];
        _subScrollView.delegate = self;
        _subScrollView.backgroundColor = [UIColor greenColor];
        [self.view addSubview:_subScrollView];
    }
    return _subScrollView;
}
- (DDDetailsBottomView *)buyView
{
    weak_Self(self);
    if (!_buyView) {
        _buyView = [[DDDetailsBottomView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        _buyView.delegate = self;
        [self.view addSubview:_buyView];
        [_buyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(weakSelf.view);
            make.height.equalTo(@50);
        }];
    }
    return _buyView;
}
- (DDDetailsDescriptionView *)descriptionView
{
    if (!_descriptionView) {
        _descriptionView = [[DDDetailsDescriptionView alloc]initWithFrame:CGRectMake(0, 45, ScreenWidth, _subScrollView.bounds.size.height-45)];
        _descriptionView.delegate = self;
        [_subScrollView addSubview:_descriptionView];
    }
    return _descriptionView;
}
- (void)descriptionView:(DDDetailsDescriptionView *)view refreshComment:(DingDongCommentType)type
{
    NSInteger grade = 0;
    switch (type) {
        case DingDongCommentTypeAll:
            grade = -1;
            break;
        case DingDongCommentTypePositive:
            grade = 3;
            break;
        case DingDongCommentTypeNeutral:
            grade = 2;
            break;
        case DingDongCommentTypeNegative:
            grade = 1;
            break;
        default:
            break;
    }
    [self fetchCommentList:grade commentViewType:@"bot"];
}
- (void)layoutDetailsView
{
    _topHeight = ScreenWidth+74+10+60+10+100+10+ScreenWidth/5.0+10+50;
    self.navigationTabView = [[KSTabButtonView alloc]initWithFrame:CGRectMake(ScreenWidth/2.0-90, 0, 180, 44)];
    _navigationTabView.showIntervalLine = NO;
    _navigationTabView.selectedColor = RGBColor(43, 43, 43);
    _navigationTabView.items = @[@"Product",@"Details",@"Review"];
    _navigationTabView.delegate = self;
    _navigationTabView.tag = 1001;
    _navigationTabView.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = _navigationTabView;
    
    self.navBarView.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.bgScrollView.backgroundColor = RGBColor(237, 237, 237);
    self.subScrollView.backgroundColor = RGBColor(237, 237, 237);

    self.buyView.backgroundColor = [UIColor whiteColor];
    [_bgScrollView setContentSize:CGSizeMake(ScreenWidth*3, _topHeight)];

    self.rightItemBtn = [[UIButton alloc] init];
    [_rightItemBtn setBackgroundImage:LoadImage(@"category_cart") forState:UIControlStateNormal];
    [_rightItemBtn setFrame:CGRectMake(0, 0, 22, 22)];
    _rightItemBtn.shouldHideBadgeAtZero = YES;
    [_rightItemBtn addTarget:self action:@selector(gotoCart:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:_rightItemBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    weak_Self(self);
    MJRefreshNormalHeader* RheaderView = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self backToFirstPageAnimation]; // 返回基本详情界面的动画
        [self.subScrollView.mj_header endRefreshing];
    }];
    RheaderView.lastUpdatedTimeLabel.hidden = YES;
    [RheaderView setTitle:@"Pull,back to details" forState:MJRefreshStateIdle];
    [RheaderView setTitle:@"" forState:MJRefreshStateRefreshing];
    [RheaderView setTitle:@"Release,back to details" forState:MJRefreshStatePulling];
    _subScrollView.mj_header = RheaderView;
    
    self.detailsTitleView = [[DDDetailsTitleView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 450)];
    [_bgScrollView addSubview:_detailsTitleView];
    [_detailsTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(weakSelf.bgScrollView);
        make.width.equalTo(@(ScreenWidth));
        make.height.equalTo(@(ScreenWidth+74));
    }];

    [_detailsTitleView updateDetailTitleViewHeight:^(CGFloat nameHeight) {
        [_detailsTitleView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(450+nameHeight-40));
        }];
        _topHeight += nameHeight-40;
        [_bgScrollView setContentSize:CGSizeMake(ScreenWidth*3, _topHeight)];
        _subScrollView.frame = CGRectMake(0, _topHeight+2, ScreenWidth, 600);
    }];
    [_detailsTitleView userPreviewLargePhotos:^(NSInteger index, NSArray *photos) {

    }];
    
    UIButton *specBackView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 80)];
    [_bgScrollView addSubview:specBackView];
    specBackView.backgroundColor = [UIColor whiteColor];
    [specBackView addTarget:self action:@selector(open) forControlEvents:UIControlEventTouchUpInside];
    [specBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(ScreenWidth));
        make.left.equalTo(weakSelf.bgScrollView);
        make.top.equalTo(weakSelf.detailsTitleView.mas_bottom).offset(10);
        make.height.equalTo(@60);
    }];
    
    self.specView = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"Chose：",[UIColor blackColor],[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
    }];
    
    [specBackView addSubview:_specView];
    [_specView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 15, 5, 15));
    }];
    
    self.shopInfoView = [[DDShopInfoView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
    [_bgScrollView addSubview:_shopInfoView];
    [_shopInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.bgScrollView);
        make.width.equalTo(@(ScreenWidth));
        make.top.equalTo(specBackView.mas_bottom).offset(10);
        make.height.equalTo(@100);
    }];
    [_shopInfoView enterInToShop:^{
        DDShopViewController *vc = StoryBoardViewController(@"Shop", @"DDShopViewController");
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];

    self.serviceMenuView = [[KSScrollMenuView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth/5+10)];
    [_bgScrollView addSubview:_serviceMenuView];
    [_serviceMenuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.shopInfoView.mas_bottom).offset(10);
        make.width.equalTo(@(ScreenWidth));
        make.left.equalTo(weakSelf.bgScrollView);
        make.height.equalTo(@(ScreenWidth/5.0+10));
    }];
    _serviceMenuView.items = @[
                               [[KSScrollMenuViewItem alloc]initWithIcon:@"details_delivery" title:@""],
                               [[KSScrollMenuViewItem alloc]initWithIcon:@"details_ensure" title:@""],
                               [[KSScrollMenuViewItem alloc]initWithIcon:@"details_hot" title:@""],
                               [[KSScrollMenuViewItem alloc]initWithIcon:@"details_price" title:@""],
                               [[KSScrollMenuViewItem alloc]initWithIcon:@"details_quality" title:@""]];
    
    self.pullBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_pullBtn setTitle:@"Pull to view details" forState:UIControlStateNormal];
    _pullBtn.backgroundColor = [UIColor whiteColor];
    _pullBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_pullBtn setTitleColor:RGBColor(150, 150, 150) forState:UIControlStateNormal];
    [_pullBtn setFrame:CGRectMake(0, 730, ScreenWidth, 50)];
    [_bgScrollView addSubview:_pullBtn];
    [_pullBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_serviceMenuView.mas_bottom);
        make.left.equalTo(weakSelf.bgScrollView);
        make.width.equalTo(@(ScreenWidth));
        make.height.equalTo(@50);
    }];
    
    self.subTabView = [[KSTabButtonView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    _subTabView.showIntervalLine = NO;
    _subTabView.items = @[@"Product Description",@"Customer Reviews"];
    _subTabView.delegate = self;
    _subTabView.tag = 1002;
    _subTabView.backgroundColor = [UIColor whiteColor];
    [_subScrollView addSubview:_subTabView];
    
    self.descriptionView.backgroundColor = RGBColor(237, 237, 237);
    
    self.detailsWebView = [[WKWebView alloc]initWithFrame:CGRectMake(ScreenWidth, 1, ScreenWidth, ScreenHeight-64-50)];
    [_bgScrollView addSubview:_detailsWebView];
    
    //初始化评论view
    self.commentView = [[DDDetailsCommentView alloc]initWithFrame:CGRectMake(ScreenWidth*2, 1, ScreenWidth, ScreenHeight-64-50)];
    _commentView.backgroundColor = RGBColor(237, 237, 237);
    _commentView.delegate = self;
    [_bgScrollView addSubview:_commentView];
    _commentView.loadMore = YES;
    self.commentPage = 1;
    [_commentView footerWithRefreshingBlock:^{
       //加载更多评论
        [_commentView endRefreshing];
    }];
}
- (void)gotoCart:(id)sender
{
    DDShoppintCartViewController *vc = StoryBoardViewController(@"Main", @"DDShoppintCartViewController");
    vc.vcType = DingDongCartControllerTypePush;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --- KSTabButtonViewDelegate
- (void)ksTabButtonView:(KSTabButtonView *)tabView didSelectIndex:(NSInteger)index
{
    self.scrollViewStartPosPoint = CGPointMake(ScreenWidth*index, 0);

    if (tabView.tag == 1001) {
        if (index == 0) {
            [self.bgScrollView setContentSize:CGSizeMake(ScreenWidth*3, _topHeight)];
        }else{
            [self.bgScrollView setContentSize:CGSizeMake(ScreenWidth*3, ScreenHeight-64-50)];
        }
        if (index ==2) {
            [self fetchCommentList:-1 commentViewType:@"top"];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_bgScrollView setContentOffset:CGPointMake(ScreenWidth*index, 0) animated:YES];
        });

    }else if (tabView.tag == 1002){
        if (index == 0) {
            self.descriptionView.showType = ShowDetailsTypeDescription;
        }else{
            self.descriptionView.showType = ShowDetailsTypeComment;
            [self fetchCommentList:-1 commentViewType:@"bot"];
        }
    }
}
#pragma mark --- CommentViewDelegate --- 评论的代理
- (void)commentView:(DDDetailsCommentView *)view refreshCommentWithType:(DingDongCommentType)type
{
    NSInteger grade = 0;
    switch (type) {
        case DingDongCommentTypeAll:
            grade = -1;
            break;
        case DingDongCommentTypePositive:
            grade = 3;
            break;
        case DingDongCommentTypeNeutral:
            grade = 2;
            break;
        case DingDongCommentTypeNegative:
            grade = 1;
            break;
            
        default:
            break;
    }
    [self fetchCommentList:grade commentViewType:@"top"];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.scrollDirection == 0){//we need to determine direction
        //use the difference between positions to determine the direction.
        if (fabs(self.scrollViewStartPosPoint.x-scrollView.contentOffset.x)<
            fabs(self.scrollViewStartPosPoint.y-scrollView.contentOffset.y)){
            //Vertical Scrolling
            self.scrollDirection = ScrollViewDirectionVertical;
            _bgScrollView.pagingEnabled = NO;
            
        } else {
            //Horitonzal Scrolling
            self.scrollDirection = ScrollViewDirectionHoritonzal;
            _bgScrollView.pagingEnabled = YES;

        }
    }
    //Update scroll position of the scrollview according to detected direction.
    if (self.scrollDirection == ScrollViewDirectionVertical) {
        scrollView.contentOffset = CGPointMake(self.scrollViewStartPosPoint.x,scrollView.contentOffset.y);
    } else if (self.scrollDirection == ScrollViewDirectionHoritonzal){
        scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x,self.scrollViewStartPosPoint.y);
    }
        
    if (scrollView == _bgScrollView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY > NAVBAR_CHANGE_POINT) {
            CGFloat alpha = MIN(0.7, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
            self.navBarView.backgroundColor = [RGBColor(255, 255, 255)colorWithAlphaComponent:alpha];
        } else {
            self.navBarView.backgroundColor = [RGBColor(255, 255, 255)colorWithAlphaComponent:0];
        }
    }


}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.scrollViewStartPosPoint = scrollView.contentOffset;
    self.scrollDirection = 0;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollDirection == ScrollViewDirectionHoritonzal) {
        CGPoint offset = scrollView.contentOffset;
        NSInteger index = offset.x/ScreenWidth;
        self.navigationTabView.currentSelectIndex = index;
    }
    self.scrollDirection =0;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (scrollView == self.bgScrollView) {
        // 能触发翻页的理想值:tableView整体的高度减去屏幕本省的高度
        CGFloat valueNum = _bgScrollView.contentSize.height -self.view.bounds.size.height;
        if ((offsetY - valueNum) > 200)
        {
            [self goToDetailAnimation]; // 进入图文详情的动画
        }
    }
    if (decelerate) {
        self.scrollDirection =0;
    }
}
// 进入详情的动画
- (void)goToDetailAnimation
{
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        _subScrollView.frame = CGRectMake(0, 65, ScreenWidth, ScreenHeight-65-50);
        _bgScrollView.frame = CGRectMake(0, -self.view.bounds.size.height, ScreenWidth, self.view.bounds.size.height);
        self.navigationTabView.alpha = 0;
    } completion:^(BOOL finished) {
        self.title = @"Details";

    }];
}


// 返回第一个界面的动画
- (void)backToFirstPageAnimation
{
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.bgScrollView.frame = CGRectMake(0, 64, ScreenWidth, self.view.bounds.size.height-64-50);
        self.subScrollView.frame = CGRectMake(0, _bgScrollView.contentSize.height, ScreenWidth, ScreenHeight);
        self.navigationTabView.alpha = 1.0;
        self.title = @"";
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark --- 选择商品规格
- (UIViewController *)rootViewController
{
    if (!_rootViewController) {
        _rootViewController =[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    return _rootViewController;
}
- (UIView *)maskLayer
{
    if (!_maskLayer) {
        UIView *maskLayer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        maskLayer.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.3];
        maskLayer.alpha = 0;
        _maskLayer = maskLayer;
        
        UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [closeButton setFrame:maskLayer.bounds];
        [closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
        [maskLayer addSubview:closeButton];
        
    }
    return _maskLayer;
}
- (UIView *)popView
{
    if (!_popView) {
        self.popView = [[DDDetailsSpecView alloc]initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight/3.0*2)];
        _popView.delegate = self;
    }
    return _popView;
}
- (void)specView:(DDDetailsSpecView *)specView addGoodsToCart:(NSDictionary *)selectDic specValue:(NSDictionary *)valueDic
{
    //加入购物车动画
    UIImageView * cartAnimView=[[UIImageView alloc] initWithFrame:CGRectMake(15, ScreenHeight/3.0-10, 90, 90)];
    [cartAnimView sd_setImageWithURL:[NSURL URLWithString:self.detailsObj.goods.thumbnail] placeholderImage:nil];
    [self.view.window addSubview:cartAnimView];
    
    weak_Self(self);
    [KKAnimationKit cartAnimationTimeInterval:1.0 inView:cartAnimView toFrame:CGRectMake(ScreenWidth-50, 40, 20, 20) complete:^{
        [cartAnimView removeFromSuperview];
        [self close];
        [self addToCart:selectDic valueDic:valueDic success:^{
            //更新购物车数量
            if (weakSelf.theGoodsAddToCart) {
                return ;
            }
            [[SystemConfig shareInstance] updateCartCountSueesss:^(NSString *count) {
                weakSelf.rightItemBtn.badgeValue = count;
                weakSelf.theGoodsAddToCart = YES;
            }];
        }];
    }];
    NSArray *valueAry = selectDic.allValues;
    __block NSString * specString = @"";
    [valueAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [specString stringByAppendingString:obj];
        if (idx<valueAry.count) {
            [specString stringByAppendingString:@","];
        }
    }];
    if (specString.length == 0) {
        self.specView.text = FormatString(@"Chosed：Have chosed %@", specView.goodsNum);
    }else
        self.specView.text = FormatString(@"Chosed：%@", specString);
    KKLog(@"选择的商品规格%@",selectDic);
}
- (void)open
{
    CheckLogin(self);
    //添加视图
    [self.rootViewController.view addSubview:self.maskLayer];
    [[UIApplication sharedApplication].keyWindow addSubview:self.popView];
    [UIApplication sharedApplication].keyWindow.backgroundColor = [UIColor blackColor];
    
    //计算位置
    CGRect frame = self.popView.frame;
    frame.origin.y -= frame.size.height;
    
    weak_Self(self);
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.rootViewController.view.layer.transform = [weakSelf getFirstTransform];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.rootViewController.view.layer.transform = [weakSelf getSecondTransform];
            weakSelf.maskLayer.alpha = 1;
            weakSelf.popView.frame = frame;
        } completion:^(BOOL finished) {
            
        }];
    }];

}
- (void)close
{
    CGRect frame = self.popView.frame;
    frame.origin.y += frame.size.height;
    
    weak_Self(self);
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.rootViewController.view.layer.transform = [weakSelf getFirstTransform];
        weakSelf.popView.frame = frame;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.rootViewController.view.layer.transform = CATransform3DIdentity;
            weakSelf.maskLayer.alpha = 0;
        } completion:^(BOOL finished) {
            [[weakSelf maskLayer]removeFromSuperview];
            [[weakSelf popView]removeFromSuperview];
            [UIApplication sharedApplication].keyWindow.backgroundColor = [UIColor whiteColor];
        }];
    }];
}
- (CATransform3D)getFirstTransform
{
    CATransform3D transform = CATransform3DIdentity;
    transform.m34 = 1.0 / -2000.0;
    transform = CATransform3DScale(transform, 0.97, 0.97, 1);
    transform = CATransform3DRotate(transform, 2.0*M_PI/180.0, 1, 0, 0);
    transform = CATransform3DTranslate(transform, 0, 0, -100.0);
    return transform;
}
- (CATransform3D)getSecondTransform
{
    CATransform3D transform = CATransform3DIdentity;
    transform.m34 = [self getFirstTransform].m34;
    transform = CATransform3DTranslate(transform, 0, self.view.frame.size.height * -0.02, 0);
    transform = CATransform3DScale(transform, 0.90, 0.90, 1.0);
    return transform;
}
- (void)dealloc
{

}
- (void)bottomView:(DDDetailsBottomView *)botView didOperationWithType:(DingDongDetailsOperationType)type
{
    CheckLogin(self);
    if (type == DingDongDetailsOperationTypeWish) {
        if (self.buyView.wished) {
            [self cancelCollectionSuccess:^{
                botView.wished = NO;
            }];
        }else{
            [self addCollectionSuccess:^{
                botView.wished = YES;
            }];
        }
    }else if (type == DingDongDetailsOperationTypeAddToCart){
        [self open];
    }
}

#pragma mark --- 添加收藏
- (void)addCollectionSuccess:(void(^)())block
{
    [[self.userManager addCollection:self.goods_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [self showMessageHUD:@"Collection success" delayHide:1.0];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)cancelCollectionSuccess:(void(^)())block
{
    [[self.userManager deleteCollection:self.goods_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [self showMessageHUD:@"Cancel collection" delayHide:1.0];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
#pragma mark --- 添加购物车
- (void)getCartCount
{
    weak_Self(self);
    [[self.cartManager getCartNum]subscribeNext:^(id x) {
        weakSelf.rightItemBtn.badgeValue = FormatString(@"%@", x);
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)addToCart:(NSDictionary *)spec valueDic:(NSDictionary *)valueDic success:(void(^)())block
{
    NSMutableArray *specAry = [[NSMutableArray alloc]initWithCapacity:0];
    for (NSString *key in spec.allKeys) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:0];
        NSString *value = spec[key];
        [dic setObject:key forKey:@"name"];
        [dic setObject:value forKey:@"value"];
        [specAry addObject:dic];
    }
    NSString *jsonSpec = [ToolKit JSONEncodeObj:specAry];
    
    __block DDProductObj *selectProduct = nil;
    [self.detailsObj.spec.productList enumerateObjectsUsingBlock:^(DDProductObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *specAry = [ToolKit JSONDecodeFromString:obj.specsvIdJson];
        KKLog(@"specAry == %@  value == %@",specAry,valueDic.allValues);
        if ([specAry isEqualToArray:valueDic.allValues]) {
            selectProduct = obj;
        }
    }];
    
    [[self.cartManager addCart:self.detailsObj.goods.goods_id num:self.popView.goodsNum name:self.detailsObj.goods.name store_id:self.detailsObj.store.store_id addon:jsonSpec product_id:selectProduct.product_id weight:selectProduct.weight]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
